/* eslint-disable no-multiple-empty-lines */
// 对账函
<template>
   <div class="reconciliation">
    <SearchBar @onSearch="handleSearch" @childFn="resetFormSearch">
      <SearchBarItem label="商户名称：" :labelLg="8">
        <Input type="text" v-model="searchData.merchantName" placeholder="请输入商户名称" clearable />
      </SearchBarItem>
      <SearchBarItem label="城市：" :labelLg="8">
        <Cascader
          class="cityInput"
          :data="cityList"
          :clearable="false"
          :load-data="cityLoadData"
          @on-change="getCityName"
          v-model="city"
          ref="address"
        ></Cascader>
      </SearchBarItem>
      <SearchBarItem label="业务场景：" :labelLg="8">
        <Select v-model="searchData.orderSource" placeholder="请选择业务场景" clearable>
          <Option v-for="(item, index) in selectScenario" :key="index" :value="item.key">{{ item.value }}</Option>
        </Select>
      </SearchBarItem>

      <SearchBarItem label="统计范围：" :labelLg="8">
        <DatePicker type="daterange" class="searchDate" ref="createDatePicker1" transfer :value="searchData.dataTime" split-panels placeholder="请选择时间区间" @on-change="searchTime"></DatePicker>
      </SearchBarItem>
      <SearchBarItem label="生成时间：" :labelLg="8">
        <DatePicker type="daterange" class="searchDate" ref="createDatePicker2" transfer :value="searchData.dataCreateTime" split-panels placeholder="请选择时间区间" @on-change="searchCleateTime"></DatePicker>
      </SearchBarItem>
    </SearchBar>
    <RemoteTable
      :namespace="namespace"
      :columns="columns"
      @onSortChange="onSortChange"
      :showPageInfo="false"
      :isFixedHeader="true"
      :selected="exportData"
      @onSelectionChange="getListChecked"
    >
      <template #extra>
        <Authc permissions="trade:settlement:cmb">
          <Button type="primary" @click="handleClick">生成对账函</Button>
        </Authc>
        <Authc permissions="trade:settlement:cmb">
          <Button type="primary" @click="handleCancel">删除</Button>
        </Authc>
      </template>

    </RemoteTable>
    <br />
    <Row>
        <Col span="12" offset="11">
            <Button
                type="primary"
                @click="loadMore"
                :disabled="isDisabledloadBtn"
                >加载更多</Button
            >
        </Col>
    </Row>

    <!-- 编辑弹窗 -->
    <Modal v-model="isShow" :visible.sync="isShow" :title="moduleTitle" width="600" class="moduleWrap">
      <Loading :loading="false">
        <Form ref="dataModule" :label-width="130" :model="dataModule" :rules="ruleValidate">

          <FormItem label="统计范围：" prop="time">
            <DatePicker type="daterange" v-model="dataModule.time" format="yyyy-MM-dd" transfer placeholder="请选择" @on-change="setDateRange"></DatePicker>
          </FormItem>

          <FormItem label="业务场景：" prop="orderSource" >
            <Select v-model="dataModule.orderSource" placeholder="请选择">
              <Option v-for="(item, index) in selectScenario" :value="item.key" :key="index">{{ item.value }}</Option>
            </Select>
          </FormItem>

          <FormItem label="商户名称" >
            <Select v-model="dataModule.merchantCode" placeholder="请选择" filterable clearable>
              <Option v-for="(item, index) in selectMerchantName" :value="item.key" :key="index">{{ item.value }}</Option>
            </Select>
          </FormItem>

          <FormItem label="">
            <div>
              注：商户名称非必选，选择代表生成单个商户的对账函，不选择代表批量生成同一场景下所有商户的对账函。
            </div>
          </FormItem>
        </Form>
      </Loading>
      <div slot="footer">
        <Button style="margin-left: 8px" @click="handleSubmitCancel('dataModule')">返回</Button>
        <Button type="primary" @click="handleSubmit('dataModule')">确定生成</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Cascader,
    TreeChild
} from "view-design";
import Loading from "@/components/Loading";
import RemoteTable from "@/components/RemoteTable";
import RemoteSelect from "@/components/RemoteSelect";
import SearchBar from "@/components/SearchBar";
import { namespace } from "../Module/reconciliationModule";
import Authc from "@/components/Authc";
import Action from "./Action";
import config from "@/utils/config";
import appService from "@/utils/appService";
import util from "@/utils/util";

export default {
  name: 'tables_page',
  components: {
    Loading,
    RemoteTable,
    SearchBar,
    SearchBarItem: SearchBar.SearchBarItem,
    RemoteSelect,
    Authc,
    Action,
    Button,
    Input,
    Modal,
    Message,
    Col,
    Row,
    Form,
    FormItem,
    DatePicker,
    Select,
    Option,
    Card,
    Cascader
  },
  data () {
    const validateDaterange = (rule, value, callback) => {
      console.log(Array.isArray(value))
      if (Array.isArray(value)) {
        if (!value[0] || !value[1]) {
          callback(new Error("日期不能为空"))
        } else {
          callback()
        }
      } else {
        callback()
      }
    };
    return {
      moduleTitle: '',
      isShow: false,
      namespace: namespace,
      isDisabledloadBtn: false /** 控制加载更多按钮 **/,
      exportData: [], /** 存放导出的数据 **/
      currentPage: 1, /** 用来控制加载更新 **/
      loading: true,
      searchData: {},
      dataModule: {},
      ruleValidate: {
        time: [{ required: true, type: 'array', message: '请选择起止日期', trigger: 'change', fields: {
          0: {type: 'date', required: true, message: '请选择起止日期'},
          1: {type: 'date', required: true, message: '请选择起止日期'}
        }}],
        orderSource: [{ required: true, message: '请选择业务场景', trigger: 'change' }]
      },
      columns: [
        {
           type: "selection",
            align: "center",
            // fixed: "left",
            minWidth: 55
        },
        {
          title: '序号',
          type: 'index',
          width: 80,
          align: 'center',
          // fixed: 'left'
        },
        {
          title: '商户名称',
          key: 'merchantName',
          minWidth: 200,
          align: 'center',
          // fixed: 'left'
        },
        {
          title: '城市',
          key: 'cityName',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '业务场景',
          key: 'orderSource',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '销售数量合计',
          key: 'sell_qty_sum',
          minWidth: 150,
          align: 'center'
        },
        {
          title: '结算单价合计(元)',
          key: 'settle_price_sum',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            let item = params.row.settle_price_sum / 100;
            return h('span', util.toMoney(item));
          }
        },
        {
          title: '结算金额合计(元)',
          key: 'settle_amount_sum',
          minWidth: 150,
          align: 'center',
          render: (h, params) => {
            let item = params.row.settle_amount_sum / 100;
            return h('span', util.toMoney(item));
          }
        },
        {
          title: '统计范围',
          key: 'count_start_date',
          minWidth: 220,
          align: 'center',
          render: (h, params) => {
            let item = params.row.count_start_date ? `${params.row.count_start_date_str} ~ ${params.row.count_end_date_str}` : '';
            return h('span', item)
          }
        },
        {
          title: '生成时间',
          key: 'createdDt',
          minWidth: 150,
          align: 'center'
        },
        {
          title: "操作",
          key: "action",
          // fixed: "right",
          align: "center",
          permissions: ["trade:settlement:cmb"],
          width: 200,
          render: function(h, data) {
            return h(Action, {
              props: {
                row: data.row
              }
            });
          }
        }
      ],
      city: [],
      cityList: [], /** 城市list */
      selectScenario: [], /** 业务场景 */
      selectMerchantName: [] /** 商户名称 */
    }
  },
  created () {
    this.getCity();
    this.getMerchListData();
    this.getScenarioData();
  },
  methods: {
    /** 获取选中的数据 **/
    getListChecked(data){
      this.exportData = data;
    },
    /** 生成对账函-统计范围时间 */
    setDateRange (value) {
      this.dataModule.count_start_date = value[0];
      this.dataModule.count_end_date = value[1];
    },
    // 范围统计
    searchTime (date, type) {
      this.searchData.count_start_date = date ? date[0] : '';
      this.searchData.count_end_date = date ? date[1] : '';
    },
    // 生成时间
    searchCleateTime (date, type) {
      this.searchData.created_start_dt = date ? date[0] : '';
      this.searchData.created_end_dt = date ? date[1] : '';
    },
    /** 城市列表 */
    getCityName (item, selectedData) {
      if (item.length == 2) {
        this.searchData.cityName = selectedData[1].label;
        this.city = [item[1]]
      } else if (item.length == 1) {
        this.searchData.cityName = selectedData[0].label;
        this.city = [item[0]]
      }
    },

    // 城市
    async getCity() {
      try {
        let params = {
          pid: 1
        }
        let res = await this.$store.dispatch(`${namespace}/getCityData`, params);
        console.log(res)
        if (res.data.ret === 0) {
          let data = res.data.data;
          this.cityList = res.data.data.map(({ name, pid, adcode, id }) => {
            if (["北京", "天津", "上海", "重庆", "澳门", "香港" ].includes(name)) {
              return {
                label: name,
                value: id
              };
            } else {
              return {
                  label: name,
                  value: id,
                  children: [],
                  loading: false
              };
            }
          });
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    /** 城市市级区域 */
    async cityLoadData(item, callback) {
        try {
            let id = {
                pid: item.value
            };
            item.loading = true;
            let res = await this.$store.dispatch(`${namespace}/getCityData`, id );
            if (res.data.ret == 0) {
                item.children = res.data.data.map(
                    ({ name, pid, adcode, id }) => {
                        return {
                            label: name,
                            value: id
                        };
                    }
                );
                item.loading = false;
                callback();
            }
        } catch (error) {
            this.$Message.error({
                content: error
            })
        }
    },

    /** 商户 */
    async getMerchListData () {
      try {
        let params = {
          currentPage: 1,
          pageSize: 9999
        }
        let res = await this.$store.dispatch(`${namespace}/getMerchList`, params );
        if (res.data.ret === 0) {
          let data = res.data.data.list;
          this.selectMerchantName = data.map(({ merchantName, merchantCode}) => {
            return {
              value: merchantName,
              key: merchantCode
            }
          })
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    /** 业务场景 */
    async getScenarioData () {
      try {
        let res = await this.$store.dispatch(`${namespace}/getScenarioList` );
        if (res.data.ret === 0) {
          let data = res.data.data.merchantScenario;
          this.selectScenario = data;
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },

    // 清空事件；
    resetFormSearch() {
      this.$set(this.searchData, 'merchantName', '');
      this.$set(this.searchData, 'cityName', '');
      this.$set(this.searchData, 'orderSource', '');
      this.$set(this.searchData, "city", []);
      this.$refs.address.clearSelect();

      this.$refs["createDatePicker1"].handleClear();
      this.$refs["createDatePicker2"].handleClear();
    },

    handleSubmitCancel (formName) {
      this.isShow = false
      this.$refs[formName].resetFields()
    },

    handleSubmit (name) {
      console.log(this.dataModule)
      this.$refs[name].validate(valid => {
        if (valid) {
            this.$store.dispatch(`${namespace}/save`, this.dataModule).then(res => {
              if (res.ret === 0) {
                this.$Message.success({
                  content: res.data
                });
                this.currentPage = 1
                this.$store.dispatch(`${namespace}/query`);
              }
            })
          this.isShow = false;
        } else {
          console.log('error submit!!')
          // return false
        }
      })
    },

    // 重置
    resetForm() {
        this.$refs['dataModule'].resetFields();
    },

    /** 生成对账函 */
    handleClick() {
      this.isShow = true;
      this.moduleTitle = '生成对账函';
      this.resetForm();
      this.dataModule = {};
    },

    /** 删除对账函 */
    async handleCancel () {
      try {
        if (this.exportData.length == 0) {
          this.$Message.warning({
            content: "请选择需要删除的对账函"
          });
          return;
        } else {
           let params = {
            statement_code_list: []
          }
          for (let i = 0; i < this.exportData.length; i++) {
            params.statement_code_list.push(this.exportData[i].statement_code)
          }
          // params.list =  params.list.join(',');

          Modal.confirm({
            render: (h, params) => {
              return h('div', [
                h('div', {
                  style:"margin-bottom:10px;vertical-align: middle;font-size: 16px;color: #17233d;font-weight: 700;"
                }, '提示'),
                h('div', {
                  class: 'selfConfirm'
                }, '是否确认删除?')
              ]);
            },
            onOk: () => {
              return this.$store.dispatch(`${namespace}/cancelRemove`, params).then(res => {
                if (res.data.ret === 0) {
                  this.$Message.success({
                    content: res.data.data
                  })
                  this.$store.dispatch(`${namespace}/query`);
                } else {
                  this.$Message.warning({
                    content: '操作失败'
                  })
                }
              })
            }
          })
        }
      } catch (error) {
        this.$Message.error({
          content: error
        })
      }
    },
    handleSearch() {
      let pageSize = {
        currentPage: 1,
        pageSize: 50
      }
      this.$store.dispatch(`${namespace}/query`, { ...this.searchData, ...pageSize });
    },
    onSortChange(sort) {
      if (sort.order === "normal") {
        this.queryParam.order = [];
      } else {
        this.queryParam.order = [sort.key + " " + sort.order];
      }
      this.handleSearch();
    },
    /** 加载更多 **/
    async loadMore() {
        try {
          let dataList = this.$store.state[namespace].pageInfo.list;

          for (let i = 0; i < dataList.length; i++) {
              dataList[i]._checked = false;
              for (let j = 0; j < this.exportData.length; j++) {
                  if (this.exportData[j].id == dataList[i].id) {
                      dataList[i]._checked = true;
                  }
              }
          }

            this.isDisabledloadBtn = true; // 每次请求都禁止按钮点击
            let obj = {
                currentPage: ++this.currentPage,
                pageSize: 50
            };
            let res = await this.$store.dispatch(
                `${namespace}/getMoreList`,
                { ...this.searchData, ...obj }
            );
            if (res.data.ret === 0) {
              let listData = res.data.data.list;
              if (listData.length != 0) {
                  this.$store.commit(`${namespace}/pushDataToList`, listData);
              } else {
                  --this.currentPage;
                  this.$Message.info({
                      content: "没有更多数据了！"
                  });
              }
              this.isDisabledloadBtn = false;
            }

        } catch (error) {
            this.$Message.error({
                content: error
            });
        }
    }
  },
  beforeDestroy() {
    this.$bus.$off('actionType');
  },
  async mounted() {
    this.$bus.$on('actionType', (data) => {
        let id = data.id;
        if (data.type === 'edit') {
          let params = {
            statementCode: id
          }
          this.$store.dispatch(`${namespace}/exportPdf`, params).then(res => {
            console.log(res, 'res')
            if (res.status == 200) {

              util.exportExcle(res, '对账函', 'pdf');
            } else {
              this.$Message.error({
                content: '导出失败'
              })
            }
          })
        }
      });
  }
}
</script>

<style lang="less" scoped>
  .reconciliation {
    .ivu-date-picker {
      width: 100%;
    }
    .cityInput {
      /deep/.ivu-input-default {
       margin-top: 4px;
      }
    }
  }
</style>
